package edu.nf.takeoutdemo.service.impl;

import edu.nf.takeoutdemo.commons.constant.StatusConstant;
import edu.nf.takeoutdemo.commons.context.BaseContext;
import edu.nf.takeoutdemo.mapper.AddressBookMapper;
import edu.nf.takeoutdemo.model.entity.AddressBook;
import edu.nf.takeoutdemo.service.AddressBookService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *
 * @author zjl
 * @date 2025/10/30
 */
@Service
@RequiredArgsConstructor
public class AddressBookServiceImpl implements AddressBookService {
    private final AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> list(AddressBook addressBook) {
        List<AddressBook> addressBookList =  addressBookMapper.list(addressBook);
        return addressBookList;
    }

    @Override
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(StatusConstant.DISABLE);
        addressBookMapper.add(addressBook);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.delete(id);
    }

    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    @Transactional
    @Override
    public void setDefault(AddressBook addressBook) {
        //先将用户所有地址设置非默认
        addressBook.setIsDefault(StatusConstant.DISABLE);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsDefaultByUserId(addressBook);

        //将要设置默认地址的地址设为默认
        addressBook.setIsDefault(StatusConstant.ENABLE);
        addressBookMapper.update(addressBook);
    }
}
